package com.jdiv.internalClasses;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.badlogic.gdx.graphics.Color;

public class FNTManager {

	public FNTManager() {
		
	}
	
	public List<Character> tratarFuente(String path) {

		FileInputStream fis = null;
		DataInputStream entrada = null;

		List<Character> listCaracter = new ArrayList<Character>();
		try {
			fis = new FileInputStream(path);
			entrada = new DataInputStream(fis);

			byte[] magic = new byte[3];
			entrada.read(magic);

			byte[] msdosend = new byte[4];
			entrada.read(msdosend);

			byte bitPerPixel = entrada.readByte();

			byte[] paleta = new byte[768];
			entrada.read(paleta);

			byte[] gamuts = new byte[576];
			entrada.read(gamuts);

			int charset = entrada.readInt();

			for (int i = 0; i < 256; i++) {
				int width = Integer.reverseBytes(entrada.readInt());
				int height = Integer.reverseBytes(entrada.readInt());
				int yOffset = Integer.reverseBytes(entrada.readInt());
				int fileOffset = Integer.reverseBytes(entrada.readInt());

				listCaracter.add(new Character(width, height, yOffset,
						fileOffset));

			}

			for (int i = 0; i < listCaracter.size(); i++) {

				Character ch = listCaracter.get(i);
				byte[] data = new byte[ch.width * ch.height];

				entrada.read(data);

				if (ch.pixmap != null) {
					int cur = 0;
					for (int y = 0; y < ch.height; y++)
						for (int x = 0; x < ch.width; x++) {
							if (data[cur] != 0) {
								int c = data[cur];
								int r = paleta[c * 3];
								int g = paleta[c * 3 + 1];
								int b = paleta[c * 3 + 2];
								ch.pixmap.setColor(new Color(r, g, b, 1));
								ch.pixmap.drawPixel(x, y);
							}
							cur++;
						}
				}
			}

		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		} catch (EOFException e) {
			System.out.println("Fin de fichero");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (entrada != null) {
					entrada.close();
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}

		return listCaracter;

	}

}
